package com.csthink.common.infrastructure.util;

import com.csthink.common.infrastructure.context.HttpContext;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-09
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class HttpContextUtil {

    private static final ThreadLocal<HttpContext> httpContextThreadLocal = new ThreadLocal<>();

    public static void create(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpContext httpContext = new HttpContext(request, response);

            httpContext.setAid(request.getHeader("x-cs-aid"));

            httpContextThreadLocal.set(httpContext);
        } catch (Exception e) {
            log.error("No customer impact. HttpContextUtil create HttpContext failed.", e);
        }
    }

    public static void remove() throws Exception {
        httpContextThreadLocal.remove();
    }

    public static HttpContext getHttpContext() {
        return httpContextThreadLocal.get();
    }

    public static HttpServletRequest getRequest() {
        HttpContext httpContext = httpContextThreadLocal.get();
        if (httpContext != null && httpContext.getRequest() != null) {
            return httpContext.getRequest();
        }

        return null;
    }

    public static HttpServletResponse getResponse() {
        HttpContext httpContext = httpContextThreadLocal.get();
        if (httpContext != null && httpContext.getResponse() != null) {
            return httpContext.getResponse();
        }

        return null;
    }
}
